<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>model_designer - Swagger UI</title>
    <link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
    <link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
    <link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
  </head>

  <body>
    <div id="swagger-ui"></div>

    <script src="./swagger-ui-bundle.js"></script>
    <script src="./swagger-ui-standalone-preset.js"></script>
    <script src="./axios.min.js"></script>

    <script type="text/javascript">
      const AlwaysEnableTryItOutPlugin = function (system) {
        return {
          components: {
            TryItOutButton: () => null,
          },
        };
      };

      window.onload = async function () {
        function getCSRF() {
          var name = 'XSRF-TOKEN=';
          var ca = document.cookie.split(';');
          for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1);
            if (c.indexOf(name) !== -1) return c.substring(name.length, c.length);
          }
          return '';
        }
        const axiosConfig = { timeout: 5000 };

        const baseUrl = '/v3/api-docs';
        let urls;

        try {
          const response = await axios.get('/management/health/discoveryComposite', axiosConfig);
          const services = response.data?.components?.discoveryClient?.details?.services;
          console.log(`Services`, services);

          if (services && services.length > 0) {
            urls = (
              await Promise.allSettled(
                services.map(async service => {
                  return axios
                    .get(`/services/${service}/management/jhiopenapigroups`, axiosConfig)
                    .then(response => {
                      if (Array.isArray(response.data)) {
                        return response.data.map(({ group, description }) => ({
                          name: description,
                          url: `/services/${service}${baseUrl}/${group}`,
                        }));
                      }
                      return undefined;
                    })
                    .catch(() => {
                      return axios
                        .get(`/services/${service}${baseUrl}`, axiosConfig)
                        .then(() => [{ url: `/services/${service}${baseUrl}`, name: `${service} (default)` }]);
                    });
                })
              )
            )
              .filter(settled => settled.status === 'fulfilled')
              .map(settled => settled.value)
              .filter(Array.isArray)
              .flat();
          }
        } catch (error) {
          console.log(error);
        }

        if (!urls || urls.length === 0) {
          const response = await axios.get('/management/jhiopenapigroups', axiosConfig);
          if (Array.isArray(response.data)) {
            urls = response.data.map(({ group, description }) => ({ name: description, url: `${baseUrl}/${group}` }));
          }
        }
        console.log(`Swagger urls`, urls);

        if (urls) {
          urls.sort(function (a, b) {
            var x = a.name.toLowerCase(),
              y = b.name.toLowerCase();
            if (x.includes('(default)')) return -1;
            if (y.includes('(default)')) return 1;
            if (x.includes('(management)')) return -1;
            if (y.includes('(management)')) return 1;
            return x < y ? -1 : x > y ? 1 : 0;
          });
        }

        // Build a system
        var ui = SwaggerUIBundle({
          urls: urls,
          url: baseUrl,
          dom_id: '#swagger-ui',
          deepLinking: true,
          filter: true,
          layout: 'StandaloneLayout',
          withCredentials: true,
          presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
          plugins: [SwaggerUIBundle.plugins.DownloadUrl, AlwaysEnableTryItOutPlugin],
          tryItOutEnabled: true,
          requestInterceptor: function (req) {
            req.headers['X-XSRF-TOKEN'] = getCSRF();
            // Remove the sample Swagger UI request body if present
            if (req.method === 'GET' && req.body === '{"additionalProp1":"string","additionalProp2":"string","additionalProp3":"string"}') {
              req.body = undefined;
            }
            return req;
          },
        });

        window.ui = ui;
      };
    </script>
  </body>
</html>
